<?php

namespace app\controller\admin\material;

use app\model\admin\basic\BasicContent;
use app\model\admin\material\MaterialGroup;
use app\model\admin\material\MaterialStyle;
use app\model\admin\material\MaterialStyleContentRelation;
use app\model\admin\material\MaterialStyleLabelRelation;
use app\model\admin\material\MaterialTitle;
use app\model\admin\material\MaterialTitleContent;
use laytp\controller\Backend;
use think\facade\Db;
use think\facade\Validate;

/**
 * Class Career
 * @package app\controller\admin\ah
 */
class Style extends Backend
{
    protected $model;
    protected $noNeedAuth = ['index', 'info', 'type', 'game', 'relation'];
    protected static $typeName = [1 => '分类', 2 => '图鉴'];


    public function initialize()
    {
        $this->model = new MaterialStyle();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 列表
     *  all_data参数的值为true时，表示查询表中所有数据集，否则进行分页查询
     * @return mixed
     */
    public function index()
    {
        $where = $this->buildSearchParams();
        $order = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            $data = $this->model->where($where)->order($order)->paginate($limit)->toArray();
            foreach ($data['data'] as &$item) {
                $temp  = explode("/",$item['jump_url']);
                $temp[count($temp)-1] = "preview/".  $temp[count($temp)-1];
                $item['preview_url'] = implode("/",$temp);
            }
        }
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        $post = $this->request->post();
        if (!$this->request->param("game_id")) {
            return $this->error("缺少游戏id");
        }
        $gameId = $this->request->param("game_id");
        try {
            Db::startTrans();
            $data = [
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s"),
                'material_game_id' => $gameId,
                'name' => $post['name'],
                'body_color' => $post['body_color'],
                'body_banner' => $post['body_banner'],
                'can_select' => $post['can_select'],
                'can_share' => $post['can_share'],
                'title_id' => $post['title_id'],

            ];
            $id = $this->model->insertGetId($data);
            if ($id) {
                if (isset($post['relation_labels']) && !empty($post['relation_labels'])) {
                    $relationLabels = explode(",", $post['relation_labels']);
                    $labelData = [];
                    foreach ($relationLabels as $item) {
                        $labelData[] = [
                            'material_style_id' => $id,
                            'label_id' => $item,
                        ];
                    }
                    if (count($labelData) > 0) (new MaterialStyleLabelRelation())->insertAll($labelData);
                }
                if (isset($post['relation_contents']) && !empty($post['relation_contents'])) {
                    $relationContents = explode(",", $post['relation_contents']);
                    $contentData = [];
                    foreach ($relationContents as $item) {
                        $contentData[] = [
                            'material_style_id' => $id,
                            'content_id' => $item,
                        ];
                    }
                    if (count($contentData) > 0) (new MaterialStyleContentRelation())->insertAll($contentData);
                }
                Db::commit();
                $this->clearCache();
                return $this->success('添加成功', $post);
            } else {
                Db::rollback();
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //编辑
    public function edit()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        if (!$info) {
            return $this->error('ID参数错误');
        }
        $post = $this->request->post();
        if (isset($post->icon) && !empty($post->icon)) {
            $post->icon = getRelativeUrl($post->icon);
        }
        foreach ($post as $k => $v) {
            $info->$k = $v;
        }
        try {
            Db::startTrans();
            $updateRes = $info->save();
            if ($updateRes) {
                $labelModel = new MaterialStyleLabelRelation();
                $contentModel = new MaterialStyleContentRelation();
                $labelModel->where('material_style_id', $id)->delete();
                $contentModel->where('material_style_id', $id)->delete();
                if (isset($post['relation_labels']) && !empty($post['relation_labels'])) {
                    $relationLabels = explode(",", $post['relation_labels']);
                    $labelData = [];
                    foreach ($relationLabels as $item) {
                        $labelData[] = [
                            'material_style_id' => $id,
                            'label_id' => $item,
                        ];
                    }
                    if (count($labelData) > 0) $labelModel->insertAll($labelData);
                }
                if (isset($post['relation_contents']) && !empty($post['relation_contents'])) {
                    $relationContents = explode(",", $post['relation_contents']);
                    $contentData = [];
                    foreach ($relationContents as $item) {
                        $contentData[] = [
                            'material_style_id' => $id,
                            'content_id' => $item,
                        ];
                    }
                    if (count($contentData) > 0) $contentModel->insertAll($contentData);
                }
                Db::commit();
                $this->clearCache();
                return $this->success('编辑成功');
            } else {
                Db::rollback();

                return $this->error('编辑失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //删除
    public function del()
    {
        $ids = array_filter($this->request->post('ids'));
        if (!$ids) {
            return $this->error('参数ids不能为空');
        }
        try {
            Db::startTrans();
            if ($this->model->destroy($ids)) {
                (new MaterialStyleLabelRelation())->whereIn("material_style_id", $ids)->delete();
                (new MaterialStyleContentRelation())->whereIn("material_style_id", $ids)->delete();
                Db::commit();
                $this->clearCache();
                return $this->success('数据删除成功');
            } else {
                Db::rollback();
                return $this->error('数据删除失败');
            }

        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    public function info()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        if (is_object($info)) $info = $info->toArray();
        $info['game'] = Db::name("material_game")->where("id", $info['material_game_id'])->find();
        $info['relation_labels'] = implode(",", (new MaterialStyleLabelRelation())->where('material_style_id', $id)->column("label_id"));
        $info['relation_contents'] = implode(",", (new MaterialStyleContentRelation())->where('material_style_id', $id)->column("content_id"));
        return $this->success('获取成功', $info);
    }

    public function type()
    {
        $data = [];
        foreach (self::$typeName as $key => $item) {
            $data[] = [
                'name' => $item, 'value' => $key
            ];
        }
        return $this->success('获取关联内容', $data);
    }

    public function game()
    {
        //获取游戏的样式
        $gameId = $this->request->param('game_id');
        $info = [];
        $info['game'] = Db::name("material_game")->where("id", $gameId)->find();
        return $this->success('数据获取成功', $info);
    }

    public function relation()
    {
        $data = $this->request->param();
        //关联下级数据
        $rule = [
            'type' => 'require|in:content,group,special,material',
            'material_game_id' => 'require',
        ];
        $msg = [
            'type.require' => '请选择操作类型',
            'type.in' => '操作类型格式错误',
            'material_game_id.require' => '请选择游戏id',
        ];
        $validate = Validate::rule($rule)->message($msg);
        $result = $validate->check($data);
        if (!$result) {
            return $this->error($validate->getError());
        }
        $styleList = $this->model->where("material_game_id", $data['material_game_id'])->where("status", 1)->select()->toArray();
        $ids = array_column($styleList, "id");
        $childrenData = [];
        switch ($data['type']) {
            //查找该游戏下面所有的模板以及关联的字段
            case "content":
                $contentsIds = (new MaterialStyleContentRelation())->whereIn("material_style_id", $ids)->select()->toArray();
                $contentList = (new MaterialTitleContent())->with("title")->whereIn("id", array_column($contentsIds, "content_id"))->select()->toArray();
                foreach ($contentList as $key => $item) {
                    if ($item['title_status'] == 2) {
                        unset($contentList[$key]);
                    }
                }
                $contentList = array_combine(array_column($contentList, "id"), $contentList);
                foreach ($contentsIds as $item) {
                    if (isset($contentList[$item['content_id']])) {
                        $childrenData[$item['material_style_id']][] = [
                            "id" => $contentList[$item['content_id']]['id'],
                            "pid" => "s" . $item['material_style_id'],
                            "name" => $contentList[$item['content_id']]['name'],
                        ];
                    }
                }
                foreach ($styleList as $key=>&$item) {
                    $item['pid'] = 0;
                    if (isset($childrenData[$item['id']])) {
                        $item['children'] = $childrenData[$item['id']];
                        $item['id'] = "s" . $item['id'];
                    }else{
                        unset($styleList[$key]);
                    }
                }
                return $this->success("获取成功", $styleList);
            case "group":
                $groups = (new MaterialGroup())->where("status", 1)->whereIn("material_style_id", $ids)->column("*", "id");
                foreach ($groups as $item) {
                    $childrenData[$item['material_style_id']][] = [
                        "id" => $item['id'],
                        "pid" => "s" . $item['material_style_id'],
                        "name" => $item['name'],
                    ];
                }
                foreach ($styleList as $key=>&$item) {
                    $item['pid'] = 0;
                    if (isset($childrenData[$item['id']])) {
                        $item['children'] = $childrenData[$item['id']];
                        $item['id'] = "s" . $item['id'];
                    }else{
                        unset($styleList[$key]);
                    }
                }
                return $this->success("获取成功", $styleList);
            case "special":
                $specials = Db::name("material_special")->group("material_style_id,material_unit")->where("status", 1)->whereIn("material_style_id", $ids)->select()->toArray();
                foreach ($specials as $item) {
                    $childrenData[$item['material_style_id']][] = [
                        "id" => $item['material_style_id']."-".$item['material_unit'],
                        "pid" => "s" . $item['material_style_id'],
                        "name" => $item['material_unit'],
                    ];
                }
                foreach ($styleList as $key=>&$item) {
                    $item['pid'] = 0;
                    if (isset($childrenData[$item['id']])) {
                        $item['children'] = $childrenData[$item['id']];
                        $item['id'] = "s" . $item['id'];
                    }else{
                        unset($styleList[$key]);
                    }
                }
                return $this->success("获取成功", $styleList);
            case "material":
                $titleIds = array_column($styleList,"title_id");
                $titleContents = (new MaterialTitle())
                    ->whereIn("id",$titleIds)->where("status",1)->where("type",2)->column("content_ids","id");
                $contentIds = [];
                foreach ($titleContents as &$item){
                    $item = explode(",",$item);
                    $contentIds = array_merge($contentIds,$item);
                }
                $contents = (new BasicContent())->whereIn("id",array_unique($contentIds))->where("status",1)->column("name","id");
                foreach ($titleContents as $key=>$item) {
                    foreach ($item as $i){
                        if(isset($contents[$i])){
                            $childrenData[$key][] = [
                                "id" => $i,
                                "pid" => "s" . $key,
                                "name" => $contents[$i],
                            ];
                        }
                    }
                }
                foreach ($styleList as $key=>&$item){
                    $item['pid'] = 0;
                    if (isset($childrenData[$item['title_id']])) {
                        $item['children'] = $childrenData[$item['title_id']];
                        $item['id'] = "s" . $item['title_id'];
                    }else{
                        unset($styleList[$key]);
                    }
                }
                return $this->success("获取成功", $styleList);
        }
    }
}